package com.example.mydemoapplication;

import android.app.Activity;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import com.example.mydemoapplication.view.IDownloadView;

import java.lang.ref.WeakReference;

/**
 * 弱引用Handler
 */
public class CountDownTimeHandler extends Handler {
    final WeakReference<IDownloadView> mWeakReference;
    public String TAG = "MyDemoApplication:CountDownTimeHandler";
    public CountDownTimeHandler(IDownloadView downloadView) {//构造方法传入activity类
        mWeakReference = new WeakReference<>(downloadView);
    }

    @Override
    public void handleMessage(Message msg) {
        super.handleMessage(msg);

        Log.d(TAG, "mWeakReference: " + mWeakReference);
        IDownloadView downloadView = mWeakReference.get();//获取到acitivy实例，方便拿到控件
        Log.d(TAG, "activity: " + downloadView);

        switch (msg.what){
            case 1004:
                int value = msg.arg1;

                if(value == 0){
                    downloadView.onUpdateDownloadButton("下载中", 1);
                }else if(value == 10){
                    downloadView.onUpdateDownloadButton("下载完成 点击重新下载", 2);
                }
                downloadView.onUpdateProgress(value++);
                //activity.tv_countdowntime.setText(String.valueOf(value--));
                if (value <= 10){
//                        sendEmptyMessageDelayed(1004,1000);//报错
                    //需要再次创建Message，从消息池obtain中获取value值。再次发送
                    Message message = Message.obtain();
                    message.what = 1004;
                    message.arg1 = value;
                    sendMessageDelayed(message,1000);
                }
                break;
            case 1005:
                downloadView.onUpdateProgress(0);
                break;
        }
    }
}